#!/usr/bin/env python
# -*- coding:utf-8 -*-

import math

from app import db
from controller.commentInfoController import CommentInfoController
from models.commentInfoModel import CommentInfo
from models.userInfoModel import UserInfo
from models.passageInfoModel import PassageInfo
from models.upvoteInfoModel import UpvoteInfo
from utils import commons
from utils.response_code import RET, error_map_EN
from utils.loggings import loggings
from sqlalchemy.orm import aliased


class CommentInfoService(CommentInfoController):
    @classmethod
    def joint_query(cls, **kwargs):
        try:
            filter_list = []
            filter_list.append(cls.IsDelete == 0)
            if kwargs.get('AutoID'):
                filter_list.append(cls.AutoID == kwargs.get('AutoID'))
            if kwargs.get('CommentPostID'):
                filter_list.append(cls.CommentPostID == kwargs.get('CommentPostID'))
            if kwargs.get('CommentUserName'):
                filter_list.append(cls.CommentUserName == kwargs.get('CommentUserName'))
            if kwargs.get('CommentUserID'):
                filter_list.append(cls.CommentUserID == kwargs.get('CommentUserID'))
            if kwargs.get('CommentContent'):
                filter_list.append(cls.CommentContent == kwargs.get('CommentContent'))
            if kwargs.get('FaceImg'):
                filter_list.append(cls.FaceImg == kwargs.get('FaceImg'))
            if kwargs.get('CommentParent'):
                filter_list.append(cls.CommentParent == kwargs.get('CommentParent'))
            if kwargs.get('IsDelete'):
                filter_list.append(cls.IsDelete == kwargs.get('IsDelete'))
            if kwargs.get('CreateTime'):
                filter_list.append(cls.CreateTime == kwargs.get('CreateTime'))
            if kwargs.get('ModifyTime'):
                filter_list.append(cls.ModifyTime == kwargs.get('ModifyTime'))

            page = int(kwargs.get('Page', 1))
            size = int(kwargs.get('Size', 10))

            commentInfo_info = db.session.query(CommentInfo.AutoID, CommentInfo.CommentPostID,
                                                CommentInfo.CommentUserName, CommentInfo.CommentUserID,
                                                CommentInfo.CommentContent, CommentInfo.FaceImg,
                                                CommentInfo.CommentParent, CommentInfo.IsDelete, CommentInfo.CreateTime,
                                                CommentInfo.ModifyTime).filter(*filter_list)

            count = commentInfo_info.count()
            pages = math.ceil(count / size)
            commentInfo_info = commentInfo_info.limit(size).offset((page - 1) * size).all()

            if not commentInfo_info:
                return {'code': RET.NODATA, 'message': error_map_EN[RET.NODATA], 'error': 'No data to update'}

            # 处理返回的数据
            results = commons.query_to_dict(commentInfo_info)
            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'totalCount': count, 'totalPage': pages,
                    'data': results}

        except Exception as e:
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'error': str(e)}
        finally:
            db.session.close()

    @classmethod
    def getallcomment(cls, **kwargs):
        try:
            filter_list = []
            filter_list.append(cls.IsDelete == 0)
            if kwargs.get('CommentPostID'):
                filter_list.append(cls.CommentPostID == kwargs.get('CommentPostID'))

            page = int(kwargs.get('Page', 1))
            size = int(kwargs.get('Size', 10))
            ParentCommentInfo = aliased(CommentInfo, name='ParentCommentInfo')
            ParentUserInfo = aliased(UserInfo, name='ParentUserInfo')
            # 先查询所有主评价
            filter_list.append(cls.CommentParent.is_(None))
            commentInfo_info = db.session.query(CommentInfo.AutoID, CommentInfo.CommentPostID,
                                                UserInfo.UserNickName.label('CommentUserName'),
                                                CommentInfo.CommentUserID,
                                                CommentInfo.CommentContent, UserInfo.FaceImg,
                                                CommentInfo.CommentParent, CommentInfo.IsDelete, CommentInfo.CreateTime,
                                                CommentInfo.ModifyTime).join(UserInfo,
                                                                             UserInfo.UserID == CommentInfo.CommentUserID).filter(
                *filter_list).order_by(
                cls.CreateTime.asc())

            count = commentInfo_info.count()
            pages = math.ceil(count / size)
            commentInfo_info = commentInfo_info.limit(size).offset((page - 1) * size).all()

            if not commentInfo_info:
                return {'code': RET.NODATA, 'message': error_map_EN[RET.NODATA], 'error': 'No data to update'}

            # 处理返回的数据
            results = commons.query_to_dict(commentInfo_info)
            print(results)
            # 处理每一个主评论将子评论包含进去
            for i in range(0, len(results)):

                child_commentInfo_info = db.session.query(CommentInfo.AutoID, CommentInfo.CommentPostID,
                                                          UserInfo.UserNickName.label('CommentUserName'),
                                                          CommentInfo.CommentUserID,
                                                          CommentInfo.CommentContent, UserInfo.FaceImg,
                                                          CommentInfo.CommentParent, CommentInfo.CommentRoot
                                                          , CommentInfo.IsDelete,
                                                          CommentInfo.CreateTime,
                                                          CommentInfo.ModifyTime,
                                                          ParentUserInfo.UserNickName.label(
                                                              'ParentUserName')).join(UserInfo,
                                                                                      UserInfo.UserID == CommentInfo.CommentUserID).join(ParentCommentInfo,
                                                                                                   ParentCommentInfo.AutoID == CommentInfo.CommentParent).join(
                    ParentUserInfo, ParentUserInfo.UserID == ParentCommentInfo.CommentUserID).filter(
                    db.and_(CommentInfo.IsDelete == 0, CommentInfo.CommentRoot == results[i]['AutoID'],
                            CommentInfo.CommentParent.is_not(None))).order_by(CommentInfo.CreateTime.asc())

                child_commentInfo_info = child_commentInfo_info.all()
                if child_commentInfo_info:
                    child_results = commons.query_to_dict(child_commentInfo_info)

                    results[i]['childcomment'] = child_results


                else:
                    results[i]['childcomment'] = 'nodata'
            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'totalCount': count, 'totalPage': pages,
                    'data': results}

        except Exception as e:
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'error': str(e)}
        finally:
            db.session.close()

    @classmethod
    def addcomment(cls, **kwargs):
        try:
            filter_list = []
            filter_list.append(UserInfo.IsDelete == 0)
            if kwargs.get('CommentUserID'):
                filter_list.append(UserInfo.UserID == kwargs.get('CommentUserID'))
            author_info = db.session.query(PassageInfo.PostAuthorID, PassageInfo.CommentNum).filter(
                PassageInfo.AutoID == kwargs.get('CommentPostID'))

            author_info = author_info.first()
            if  not author_info:
                return {'code': RET.NODATA, 'message': error_map_EN[RET.NODATA], 'error': 'No data '}
            # 处理返回的数据
            author_info = commons.query_to_dict(author_info)

            # 更新评论数
            if kwargs.get('CommentParent') is None:
                commentupdate = {
                    'AutoID': kwargs.get('CommentPostID'),
                    'CommentNum': int(author_info.get('CommentNum')) + 1
                }
                from controller.passageInfoController import PassageInfoController
                PassageInfoController.update(**commentupdate)

            # 自己评论自己置为已读不再显示在消息通知中
            if author_info.get('PostAuthorID') == kwargs.get('CommentUserID') and kwargs.get('CommentParent') is None:
                kwargs['IsRead'] = 1
            else:
                kwargs['IsRead'] = 0
            # 自己回复自己置为已读不再显示在消息通知中
            if kwargs.get('CommentParent'):
                filter_list2 = [cls.IsDelete == 0, cls.AutoID == kwargs.get('CommentParent')]
                user_info = db.session.query(CommentInfo.CommentUserID, CommentInfo.CommentContent).filter(
                    *filter_list2)
                user_info = user_info.first()
                if not user_info:
                    return {'code': RET.NODATA, 'message': error_map_EN[RET.NODATA], 'error': 'No data '}
                results2 = commons.query_to_dict(user_info)
                if results2.get('CommentUserID') == kwargs.get('CommentUserID'):
                    kwargs['IsRead'] = 1
                else:
                    kwargs['IsRead'] = 0
            add_data = cls.add(**kwargs)
            add_data = add_data.get('data')

            if add_data.get('CommentRoot') is None:
                update_data = {
                    'AutoID': add_data.get('AutoID'),
                    'CommentRoot': add_data.get('AutoID')
                }
                cls.update(**update_data)
                add_data['CommentRoot'] = add_data.get('AutoID')
            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'data': add_data
                    }

        except Exception as e:
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'error': str(e)}
        finally:
            db.session.close()

    @classmethod
    def messageinform(cls, **kwargs):
        try:
            ChildComment = aliased(CommentInfo, name='ChildComment')
            # 主评价查询条件
            filter_list = [cls.IsDelete == 0, PassageInfo.IsDelete == 0, UserInfo.IsDelete == 0, cls.IsRead == 0,
                           cls.CommentParent.is_(None)]
            if kwargs.get('UserID'):
                filter_list.append(UserInfo.UserID == kwargs.get('UserID'))

            commentInfo_info = db.session.query(UserInfo.UserNickName, UserInfo.UserID).join(PassageInfo,
                                                                                             PassageInfo.PostAuthorID == UserInfo.UserID).join(
                CommentInfo, CommentInfo.CommentPostID == PassageInfo.AutoID).filter(*filter_list)
            # 主评论个数
            commentInfo_info = commentInfo_info.count()

            # 回复评价查询条件
            filter_list2 = [cls.IsDelete == 0, PassageInfo.IsDelete == 0, CommentInfo.IsRead == 0,
                            ChildComment.IsDelete == 0, CommentInfo.CommentParent.is_not(None)]
            if kwargs.get('UserID'):
                filter_list2.append(ChildComment.CommentUserID == kwargs.get('UserID'))

            reply_info = db.session.query(CommentInfo.CommentContent, ChildComment.CommentContent.label('childcontent'),
                                          PassageInfo.PostAuthorID).join(ChildComment,
                                                                         ChildComment.AutoID == CommentInfo.CommentParent).join(
                PassageInfo, CommentInfo.CommentPostID == PassageInfo.AutoID).filter(*filter_list2)
            resultinfo = commons.query_to_dict(reply_info.all())
            print(resultinfo)

            reply_info = reply_info.count()
            # 点赞获取个数
            filter_list3 = [UpvoteInfo.IsRead == 0, UpvoteInfo.IsDelete == 0, UserInfo.IsDelete == 0,
                            PassageInfo.IsDelete == 0]
            if kwargs.get('UserID'):
                filter_list3.append(UserInfo.UserID == kwargs.get('UserID'))

            upvote_info = db.session.query(UserInfo.UserNickName, UserInfo.UserID, UpvoteInfo.UUserID).join(PassageInfo,
                                                                                                            PassageInfo.PostAuthorID == UserInfo.UserID).join(
                UpvoteInfo, UpvoteInfo.PassageID == PassageInfo.AutoID).filter(*filter_list3)
            upvote_info = upvote_info.count()
            # 处理返回的数据
            results = {
                'commentNUM': commentInfo_info,
                'replyNUM': reply_info,
                'upvoteNUM': upvote_info,
                'totalNUM': commentInfo_info + reply_info + upvote_info
            }
            return {'code': RET.OK, 'message': error_map_EN[RET.OK],
                    'data': results}

        except Exception as e:
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'error': str(e)}
        finally:
            db.session.close()
